package xin.marcher.module.seller.repository;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import xin.marcher.framework.common.util.data.DataCuttingUtil;
import xin.marcher.module.common.constants.construction.ProductConstants;
import xin.marcher.module.common.constants.seller.SellerRedisKeyConstants;
import xin.marcher.module.common.constants.seller.SkuSellerRelationConstants;
import xin.marcher.module.common.core.PageResult;
import xin.marcher.module.common.enums.YesOrNoEnum;
import xin.marcher.module.common.enums.seller.SellerInfoStatusEnum;
import xin.marcher.module.common.enums.seller.SellerPositionEnum;
import xin.marcher.module.common.enums.seller.SellerTypeEnum;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.common.exception.CommonErrorCodeEnum;
import xin.marcher.module.common.exception.ProductBizException;
import xin.marcher.module.common.exception.ProductErrorCodeEnum;
import xin.marcher.module.common.redis.RedisCache;
import xin.marcher.module.common.redis.RedisLock;
import xin.marcher.module.common.utils.IDUtils;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.seller.converter.SellerAccountConverter;
import xin.marcher.module.seller.converter.SellerGroupConverter;
import xin.marcher.module.seller.converter.SellerGroupRelationConverter;
import xin.marcher.module.seller.converter.SellerInfoConverter;
import xin.marcher.module.seller.domain.dto.SellerAccountDTO;
import xin.marcher.module.seller.domain.dto.SellerGroupRelationDTO;
import xin.marcher.module.seller.domain.dto.SellerInfoDTO;
import xin.marcher.module.seller.domain.entity.*;
import xin.marcher.module.seller.domain.request.SellerAccountRequest;
import xin.marcher.module.seller.domain.request.SellerGroupRelationRequest;
import xin.marcher.module.seller.domain.request.SellerGroupRequest;
import xin.marcher.module.seller.domain.request.SellerInfoRequest;
import xin.marcher.module.seller.domain.response.SellerGroupResponse;
import xin.marcher.module.seller.domain.response.SellerInfoResponse;
import xin.marcher.module.seller.mapper.*;
import xin.marcher.module.seller.mq.message.PreheatSellerMessage;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 *
 */
@Slf4j
@Repository
public class SellerRepository {

    @Resource
    private RedisCache redisCache;

    @Resource
    private RedisLock redisLock;

    @Resource
    private SellerInfoMapper sellerInfoMapper;

    @Resource
    private SellerGroupMapper sellerGroupMapper;

    @Resource
    private SellerGroupRelationMapper sellerGroupRelationMapper;

    @Resource
    private SellerAccountMapper sellerAccountMapper;

    @Resource
    private SellerAutoNoMapper sellerAutoNoMapper;

    @Resource
    private NationalCodeMapper nationalCodeMapper;

    @Resource
    private SellerInfoConverter sellerInfoConverter;

    @Resource
    private SellerGroupConverter sellerGroupConverter;

    @Resource
    private SellerGroupRelationConverter sellerGroupRelationConverter;

    @Resource
    private SellerAccountConverter sellerAccountConverter;

    /**
     * 自营卖家叶子结点sellerCode生成
     * 格式：父卖家（区县）的首拼-4位随机数，如：西湖区 -> XH-1001
     *
     * @param prefix 前缀
     * @param width  位数
     * @return
     */
    public String generateSellerNo(String prefix, Integer width) {
        SellerAutoNoDO sellerAutoNoDO = new SellerAutoNoDO();
        sellerAutoNoMapper.insert(sellerAutoNoDO);
        Long autoNo = sellerAutoNoDO.getId();
        if (Objects.isNull(autoNo)) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }

        return prefix + IDUtils.genId(autoNo, width);
    }

    /**
     * sellerId、sellerGroupId生成
     * sellerId格式：20开头，6位随机数
     * sellerGroupId格式：30开头，4位随机数
     *
     * @param prefix
     * @param width
     * @return
     */
    public Long generateSellerId(String prefix, Integer width) {
        return Long.parseLong(generateSellerNo(prefix, width));
    }

    /**
     * 国标是否存在
     *
     * @param sellerCode
     * @return 存在：true；不存在：false
     */
    public Boolean sellerCodeExists(String sellerCode) {
        LambdaQueryWrapper<NationalCodeDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(NationalCodeDO::getId, sellerCode);

        Integer count = nationalCodeMapper.selectCount(queryWrapper);
        return Objects.nonNull(count) && count > 0;
    }

    /**
     * 父卖家是否存在，初始化的时候卖家树已经生成，这里只需要检查上一级卖家，不需要去递归检查所有上级卖家链路
     *
     * @param parentId
     * @return
     */
    public SellerInfoDO sellerParentExists(Integer parentId) {
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SellerInfoDO::getSellerId, parentId);

        return sellerInfoMapper.selectOne(queryWrapper);
    }

    /**
     * 新增卖家
     *
     * @param request
     */
    public void saveSellerInfo(SellerInfoRequest request) {
        // 是否存在该记录
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SellerInfoDO::getSellerId, request.getSellerId());
        int count = sellerInfoMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }

        // DO对象初始化
        SellerInfoDO sellerInfo = initSellerInfoDO(request);
        // 保存到缓存
        redisCache.set(SellerRedisKeyConstants.SELLER_INFO_LIST + sellerInfo.getSellerId(), JSON.toJSONString(sellerInfo), -1);
        // 新卖家落库
        count = sellerInfoMapper.insert(sellerInfo);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 新增卖家时初始化卖家信息
     *
     * @param request
     * @return
     */
    private SellerInfoDO initSellerInfoDO(SellerInfoRequest request) {
        SellerInfoDO sellerInfo = sellerInfoConverter.requestToEntity(request);
        sellerInfo.setSellerPosition(SellerPositionEnum.STORAGE.getCode());
        sellerInfo.setSellerType(SellerTypeEnum.SELF.getCode());
        sellerInfo.setLastNode(YesOrNoEnum.YES.getCode());
        sellerInfo.initCommon();
        return sellerInfo;
    }

    /**
     * 批量新增卖家
     *
     * @param sellerInfoList
     */
    public void savelSellerInfoBatch(List<SellerInfoDO> sellerInfoList) {
        List<Long> sellerIdList = sellerInfoList.stream()
                .map(SellerInfoDO::getSellerId)
                .collect(Collectors.toList());

        // 是否存在该记录
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(SellerInfoDO::getSellerId, sellerIdList);
        int count = sellerInfoMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }

        // 批量插入
        count = sellerInfoMapper.insertBatch(sellerInfoList);
        if (count != sellerInfoList.size()) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 取消父卖家叶子结点状态
     *
     * @param request
     * @return
     */
    public void cancelParentSellerLastNode(SellerInfoRequest request) {
        LambdaUpdateWrapper<SellerInfoDO> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(SellerInfoDO::getLastNode, YesOrNoEnum.NO.getCode());

        updateWrapper.eq(SellerInfoDO::getSellerId, request.getParentId());
        int count = sellerInfoMapper.update(null, updateWrapper);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 修改卖家
     *
     * @param request
     */
    public void updateSellerInfo(SellerInfoRequest request) {
        // 查询出数据库卖家信息
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SellerInfoDO::getSellerId, request.getSellerId());
        SellerInfoDO sellerInfo = sellerInfoMapper.selectOne(queryWrapper);
        if (Objects.isNull(sellerInfo)) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }
        // 更新到缓存
        updateSellerInfoFromCache(request, sellerInfo);
        // 更新到数据库
        updateSellerInfoFromDB(request);
    }

    /**
     * 更新卖家信息到数据库
     *
     * @param request
     */
    private void updateSellerInfoFromDB(SellerInfoRequest request) {
        SellerInfoDO requestInfo = sellerInfoConverter.requestToEntity(request);
        LambdaUpdateWrapper<SellerInfoDO> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(SellerInfoDO::getSellerId, request.getSellerId());
        int count = sellerInfoMapper.update(requestInfo, updateWrapper);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 更新卖家信息到缓存
     *
     * @param request
     * @param sellerInfo
     */
    private void updateSellerInfoFromCache(SellerInfoRequest request, SellerInfoDO sellerInfo) {
        String redisKey = SellerRedisKeyConstants.SELLER_INFO_LIST + request.getSellerId();
        if (StringUtils.isNotEmpty(request.getSellerName())) {
            sellerInfo.setSellerName(request.getSellerName());
        }
        if (StringUtils.isNotEmpty(request.getSellerDesc())) {
            sellerInfo.setSellerDesc(request.getSellerDesc());
        }
        if (Objects.nonNull(SellerInfoStatusEnum.getByCode(request.getSellerStatus()))) {
            sellerInfo.setSellerStatus(request.getSellerStatus());
        }
        redisCache.set(redisKey, JSON.toJSONString(sellerInfo), -1);
    }


    /**
     * 根据条件分页查询出卖家列表
     *
     * @param request
     * @return
     */
    public Optional<List<SellerInfoResponse>> querySellerInfo(SellerInfoRequest request) {
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        // 类型
        queryWrapper.eq(Objects.nonNull(request.getSellerType()), SellerInfoDO::getSellerType, request.getSellerType());
        // 卖家位置（层级）
        queryWrapper.eq(Objects.nonNull(request.getSellerPosition()), SellerInfoDO::getSellerPosition, request.getSellerPosition());
        // 状态
        queryWrapper.eq(Objects.nonNull(request.getSellerStatus()), SellerInfoDO::getSellerStatus, request.getSellerStatus());
        // 卖家ID
        queryWrapper.eq(Objects.nonNull(request.getSellerId()), SellerInfoDO::getSellerId, request.getSellerId());
        // 卖家编码
        queryWrapper.eq(StringUtils.isNotEmpty(request.getSellerCode()), SellerInfoDO::getSellerCode, request.getSellerCode());
        // 卖家名称
        queryWrapper.like(StringUtils.isNotEmpty(request.getSellerName()), SellerInfoDO::getSellerName, request.getSellerName());
        // 父卖家ID
        queryWrapper.eq(Objects.nonNull(request.getParentId()), SellerInfoDO::getParentId, request.getParentId());
        // 卖家ID集合
        queryWrapper.in(CollectionUtils.isNotEmpty(request.getSellerIdList()), SellerInfoDO::getSellerId, request.getSellerIdList());

        Page<SellerInfoDO> page = new Page<>(request.getPageNo(), request.getPageSize());
        Page<SellerInfoDO> pageResult = sellerInfoMapper.selectPage(page, queryWrapper);
        if (Objects.isNull(pageResult)) {
            return Optional.of(Collections.emptyList());
        }

        return Optional.of(sellerInfoConverter.listEntityToResponse(pageResult.getRecords()));
    }

    /**
     * 检查是否存在非叶子卖家
     *
     * @param sellerIdList
     * @return true：存在；false：不存在
     */
    public Boolean checkNonLastSellerExists(List<Integer> sellerIdList) {
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SellerInfoDO::getLastNode, YesOrNoEnum.NO.getCode());
        queryWrapper.in(CollectionUtils.isNotEmpty(sellerIdList), SellerInfoDO::getSellerId, sellerIdList);

        Integer count = sellerInfoMapper.selectCount(queryWrapper);
        return Objects.nonNull(count) && count > 0;
    }

    /**
     * 删除卖家
     *
     * @param sellerIdList
     */
    public void deleteSellerInfo(List<Integer> sellerIdList) {
        // 删除缓存卖家
        List<String> redisKeyList = sellerIdList.stream().map(sellerId -> SellerRedisKeyConstants.SELLER_INFO_LIST + sellerId).collect(toList());
        redisCache.delete(redisKeyList);

        // 删除数据库卖家
        LambdaUpdateWrapper<SellerInfoDO> updateWrapper = Wrappers.lambdaUpdate();
        // 条件
        updateWrapper.in(SellerInfoDO::getSellerId, sellerIdList);
        updateWrapper.eq(SellerInfoDO::getLastNode, YesOrNoEnum.YES.getCode());
        // 删除标志
        updateWrapper.set(SellerInfoDO::getDelFlag, YesOrNoEnum.NO.getCode());
        int count = sellerInfoMapper.update(null, updateWrapper);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 新增卖家组
     *
     * @param request
     */
    public void saveSellerGroup(SellerGroupRequest request) {
        // 是否存在该记录
        LambdaQueryWrapper<SellerGroupDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SellerGroupDO::getSellerGroupId, request.getSellerGroupId());
        int count = sellerGroupMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }

        // DO对象初始化
        SellerGroupDO sellerGroup = sellerGroupConverter.requestToEntity(request);
        sellerGroup.initCommon();
        // 新卖家落库
        count = sellerGroupMapper.insert(sellerGroup);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 修改卖家组数据
     * 卖家组类型禁止修改
     *
     * @param request
     */
    public void updateSellerGroup(SellerGroupRequest request) {
        LambdaUpdateWrapper<SellerGroupDO> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(StringUtils.isNotEmpty(request.getSellerGroupName()), SellerGroupDO::getSellerGroupName, request.getSellerGroupName());
        updateWrapper.set(Objects.nonNull(request.getSellerGroupStatus()), SellerGroupDO::getSellerGroupStatus, request.getSellerGroupStatus());
        updateWrapper.eq(SellerGroupDO::getSellerGroupId, request.getSellerGroupId());

        int count = sellerGroupMapper.update(null, updateWrapper);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 查询卖家组
     *
     * @param request
     * @return
     */
    public PageResult<SellerGroupResponse> querySellerGroup(SellerGroupRequest request) {
        LambdaQueryWrapper<SellerGroupDO> queryWrapper = Wrappers.lambdaQuery();
        // 卖家组ID
        queryWrapper.eq(Objects.nonNull(request.getSellerGroupId()), SellerGroupDO::getSellerGroupId, request.getSellerGroupId());
        // 卖家组名称
        queryWrapper.like(StringUtils.isNotEmpty(request.getSellerGroupName()), SellerGroupDO::getSellerGroupName, request.getSellerGroupName());
        // 卖家组状态
        queryWrapper.eq(Objects.nonNull(request.getSellerGroupStatus()), SellerGroupDO::getSellerGroupStatus, request.getSellerGroupStatus());
        // 卖家组ID集合
        queryWrapper.in(CollectionUtils.isNotEmpty(request.getSellerGroupIdList()), SellerGroupDO::getSellerGroupId, request.getSellerGroupIdList());
        queryWrapper.eq(SellerGroupDO::getDelFlag, YesOrNoEnum.YES.getCode());
        Page<SellerGroupDO> page = new Page<>(request.getPageNo(), request.getPageSize());
        Page<SellerGroupDO> pageResult = sellerGroupMapper.selectPage(page, queryWrapper);
        if (Objects.isNull(pageResult)) {
            return new PageResult<>();
        }

        List<SellerGroupDO> groupList = pageResult.getRecords();
        List<SellerGroupResponse> sellerGroupResponseList = sellerGroupConverter.listEntityToResponse(groupList);
        return new PageResult<>(sellerGroupResponseList);

    }

    /**
     * 根据group信息查询对应的卖家信息
     *
     * @param page
     * @return
     */
    public PageResult<SellerGroupResponse> querySellerInfoByGroupList(PageResult<SellerGroupResponse> page) {
        // 提取groupIdList，用于查询对应的卖家数据信息
        List<Long> groupIdList = page.getContent()
                .stream().map(SellerGroupResponse::getSellerGroupId).collect(Collectors.toList());
        // 查询出卖家数据与卖家组id映射关系
        Map<Long, List<SellerInfoDTO>> sellerInfoMap = querySellerInfoBySellerIdList(groupIdList);

        // 组装卖家数据到响应数据体中
        List<SellerGroupResponse> sellerGroupResponseList = page.getContent().stream()
                .peek(sellerGroupResponse -> sellerGroupResponse.setSellerInfoDTOList(sellerInfoMap.get(sellerGroupResponse.getSellerGroupId())))
                .collect(Collectors.toList());
        return new PageResult<>(sellerGroupResponseList);
    }

    /**
     * 根据卖家组ID集合查询出对应的卖家集合
     *
     * @param groupIdList
     * @return
     */
    private Map<Long, List<SellerInfoDTO>> querySellerInfoBySellerIdList(List<Long> groupIdList) {
        // 卖家与卖家组关系集合
        List<SellerGroupRelationDTO> relationList = querySellerGroupRelationInfo(groupIdList);
        // 卖家ID和卖家组ID的映射关系
        Map<Long, Long> sellerGroupIdRelationMap = new HashMap<>();
        // 卖家ID集合
        List<Long> sellerIdList = new ArrayList<>();
        for (SellerGroupRelationDTO relation : relationList) {
            sellerGroupIdRelationMap.put(relation.getSellerId(), relation.getSellerGroupId());
            sellerIdList.add(relation.getSellerId());
        }
        SellerInfoRequest request = new SellerInfoRequest();
        request.setSellerIdList(sellerIdList);
        Optional<List<SellerInfoResponse>> sellerInfoResponseListOps = querySellerInfo(request);
        if (!sellerInfoResponseListOps.isPresent()) {
            return Collections.emptyMap();
        }

        List<SellerInfoResponse> sellerInfoResponseList = sellerInfoResponseListOps.get();
        Map<Long, List<SellerInfoDTO>> result = new HashMap<>();
        for (SellerInfoResponse sellerInfoResponse : sellerInfoResponseList) {
            Long groupId = sellerGroupIdRelationMap.get(sellerInfoResponse.getSellerId());

            List<SellerInfoDTO> sellerInfoList = result.get(groupId);
            if (CollectionUtils.isEmpty(sellerInfoList)) {
                sellerInfoList = new ArrayList<>();
            }
            sellerInfoList.add(sellerInfoConverter.responseToDTO(sellerInfoResponse));
            result.put(groupId, sellerInfoList);
        }
        return result;
    }

    /**
     * 批量保存卖家与卖家组信息
     *
     * @param request
     * @return
     */
    public void saveSellerGroupRelationInfo(SellerGroupRelationRequest request) {
        // 经过前置sellerId过滤，sellerId为空说明本批次的relation关系已经保存过
        // 直接返回即可
        if (CollectionUtils.isEmpty(request.getSellerIdList())) {
            return;
        }
        List<SellerGroupRelationDO> relationList = request.getSellerIdList().stream().map(sellerId -> {
            SellerGroupRelationDO relation = new SellerGroupRelationDO();
            relation.setSellerGroupId(request.getSellerGroupId());
            relation.setSellerId(sellerId);
            relation.initCommon();
            return relation;
        }).collect(Collectors.toList());

        Integer count = sellerGroupRelationMapper.insertBatch(relationList);
        if (Objects.isNull(count) || count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 保存一个卖家账户信息
     *
     * @param request
     * @return
     */
    public Boolean saveSellerAccountInfo(SellerAccountRequest request) {
        SellerAccountDO accountDO = sellerAccountConverter.convertToDO(request);
        // 初始化默认参数
        accountDO.initCommon();
        Integer count = sellerAccountMapper.insert(accountDO);

        if (count <= 0) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
        return true;
    }

    /**
     * 更新卖家账户的支付渠道信息
     *
     * @param request
     * @return
     */
    public Boolean updateSellerAccountInfo(SellerAccountRequest request) {
        SellerAccountDO accountDO = sellerAccountConverter.convertToDO(request);
        // 根据卖家id查询账户信息
        LambdaQueryWrapper<SellerAccountDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SellerAccountDO::getSellerId, accountDO.getSellerId());
        queryWrapper.eq(SellerAccountDO::getAccountNo, accountDO.getAccountNo());
        queryWrapper.eq(SellerAccountDO::getDelFlag, YesOrNoEnum.YES.getCode());
        SellerAccountDO sellerAccountDO = sellerAccountMapper.selectOne(queryWrapper);
        if (Objects.isNull(sellerAccountDO)) {
            throw new BaseBizException("该卖家的待更新账户信息不存在");
        }
        // 设置更新字段，执行更新操作
        sellerAccountDO.setPayChannel(accountDO.getPayChannel());
        sellerAccountDO.setUpdateTime(new Date());
        int count = sellerAccountMapper.updateById(sellerAccountDO);

        if (count <= 0) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
        return true;
    }

    /**
     * 根据sellerId查询所有卖家相关的账号
     *
     * @param sellerId
     * @return
     */
    public List<SellerAccountDTO> queryAccountsBySellerId(Long sellerId) {
        LambdaQueryWrapper<SellerAccountDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SellerAccountDO::getSellerId, sellerId);
        queryWrapper.eq(SellerAccountDO::getDelFlag, YesOrNoEnum.YES.getCode());
        List<SellerAccountDO> accountDOS = sellerAccountMapper.selectList(queryWrapper);

        // 如果查询结果为空集合或者null
        if (CollectionUtils.isEmpty(accountDOS)) {
            return new ArrayList<>();
        }
        return sellerAccountConverter.convertAccountsTODTO(accountDOS);
    }

    /**
     * 逻辑删除一个账号
     *
     * @param request
     * @return
     */
    public Boolean deleteAccount(SellerAccountRequest request) {
        SellerAccountDO accountDO = sellerAccountConverter.convertToDO(request);
        // 根据卖家id查询账户信息
        LambdaQueryWrapper<SellerAccountDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SellerAccountDO::getSellerId, accountDO.getSellerId());
        queryWrapper.eq(SellerAccountDO::getAccountNo, accountDO.getAccountNo());
        queryWrapper.eq(SellerAccountDO::getDelFlag, YesOrNoEnum.YES.getCode());
        SellerAccountDO sellerAccountDO = sellerAccountMapper.selectOne(queryWrapper);
        if (Objects.isNull(sellerAccountDO)) {
            throw new BaseBizException("待删除账户信息不存在");
        }
        // 设置账号信息为失效
        sellerAccountDO.setDelFlag(YesOrNoEnum.NO.getCode());
        sellerAccountDO.setUpdateTime(new Date());
        int count = sellerAccountMapper.updateById(sellerAccountDO);

        if (count <= 0) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
        return true;
    }

    /**
     * 根据卖家组id列表，卖家组类型查询卖家与卖家关系
     *
     * @param
     * @return
     */
    public List<SellerGroupRelationDTO> querySellerGroupRelationInfo(SellerGroupRelationRequest request) {

        LambdaQueryWrapper<SellerGroupRelationDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Objects.nonNull(request.getSellerGroupId()), SellerGroupRelationDO::getSellerGroupId, request.getSellerGroupId());

        // 分页查询存放数据的总集合
        List<SellerGroupRelationDO> results = new ArrayList<>();

        Page<SellerGroupRelationDO> page = new Page<>(request.getPageNo(), request.getPageSize());
        // 查询分页数据
        Page<SellerGroupRelationDO> pageResult = sellerGroupRelationMapper.selectPage(page, queryWrapper);
        results.addAll(pageResult.getRecords());

        return sellerGroupRelationConverter.convertAccountsTODTO(results);
    }

    /**
     * 查询卖家与卖家关系集合
     *
     * @param groupIdList
     * @return
     */
    private List<SellerGroupRelationDTO> querySellerGroupRelationInfo(List<Long> groupIdList) {
        List<SellerGroupRelationDO> relationList = new ArrayList<>();
        // 一次最大查询200个数据，多个分页查询,这里做数据切割
        List<List<Long>> splitList = DataCuttingUtil.dataCuttingString(groupIdList, ProductConstants.QUERY_ITEM_MAX_COUNT);
        for (List<Long> groupIds : splitList) {
            LambdaQueryWrapper<SellerGroupRelationDO> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(Objects.nonNull(groupIds), SellerGroupRelationDO::getSellerGroupId, groupIds);
            List<SellerGroupRelationDO> relations = sellerGroupRelationMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(relations)) {
                relationList.addAll(relations);
            }
        }
        return sellerGroupRelationConverter.listEntityToDTO(relationList);
    }

    /**
     * 逻辑删除卖家与卖家组关系
     *
     * @param sellerIds
     * @param sellerGroupId
     * @return
     */
    public Boolean deleteRelationBySellerId(List<Long> sellerIds, Long sellerGroupId) {
        int count = sellerGroupRelationMapper
                .deleteBySellerId(sellerIds, sellerGroupId, YesOrNoEnum.NO.getCode());
        if (count <= 0) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
        return true;
    }

    /**
     * 删除卖家组
     *
     * @param sellerGroupIdList
     */
    public void deleteSellerGroup(List<Long> sellerGroupIdList) {
        LambdaUpdateWrapper<SellerGroupDO> updateWrapper = Wrappers.lambdaUpdate();
        // 条件
        updateWrapper.in(SellerGroupDO::getSellerGroupId, sellerGroupIdList);
        // 删除标志
        updateWrapper.set(SellerGroupDO::getDelFlag, YesOrNoEnum.NO.getCode());
        int count = sellerGroupMapper.update(null, updateWrapper);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 根据类型分页查询sellerId集合
     *
     * @param request
     * @return sellerID集合
     */
    public Optional<List<Long>> pageSellerIdListByType(SellerInfoRequest request) {
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        // 类型
        queryWrapper.eq(Objects.nonNull(request.getSellerType()), SellerInfoDO::getSellerType, request.getSellerType());
        // 指定查询字段
        queryWrapper.select(SellerInfoDO::getSellerId);
        Page<SellerInfoDO> page = new Page<>(request.getPageNo(), request.getPageSize());
        // 查询分页数据
        Page<SellerInfoDO> pageResult = sellerInfoMapper.selectPage(page, queryWrapper);
        if (Objects.isNull(pageResult)) {
            return Optional.empty();
        }
        // 缓存sellerIdList
        return Optional.of(pageResult.getRecords().stream().map(SellerInfoDO::getSellerId).collect(Collectors.toList()));
    }

    /**
     * 根据sellerId查询SellerInfo数据
     *
     * @param sellerId
     * @return
     */
    public Optional<SellerInfoResponse> querySellerInfoBySellerId(Long sellerId) {
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Objects.nonNull(sellerId), SellerInfoDO::getSellerId, sellerId);

        return Optional.ofNullable(sellerInfoConverter.entityToResponse(sellerInfoMapper.selectOne(queryWrapper)));
    }

    /**
     * 根据类型查询sellerIdList
     *
     * @param request
     * @return
     */
    public List<Long> getSellerIdListByType(SellerInfoRequest request) {
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        // 类型
        queryWrapper.eq(Objects.nonNull(request.getSellerType()), SellerInfoDO::getSellerType, request.getSellerType());
        // 指定查询字段
        queryWrapper.select(SellerInfoDO::getSellerId);
        // 查询分页数据
        List<SellerInfoDO> sellerInfoList = sellerInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(sellerInfoList)) {
            return Collections.emptyList();
        }

        // 缓存sellerIdList
        return sellerInfoList.stream().map(SellerInfoDO::getSellerId).collect(Collectors.toList());
    }

    /**
     * 获取下一层级卖家的sellerId
     *
     * @param parentIdList
     * @return
     */
    public List<Long> getSellerIdListByParentId(List<Long> parentIdList, Integer sellerType) {
        LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(Objects.nonNull(parentIdList), SellerInfoDO::getParentId, parentIdList);
        queryWrapper.in(SellerInfoDO::getSellerPosition,
                SellerPositionEnum.CITY.getCode(), SellerPositionEnum.REGION.getCode(), SellerPositionEnum.STORAGE.getCode());
        queryWrapper.eq(Objects.nonNull(sellerType), SellerInfoDO::getSellerType, sellerType);
        queryWrapper.eq(SellerInfoDO::getDelFlag, YesOrNoEnum.YES.getCode());
        queryWrapper.select(SellerInfoDO::getSellerId);

        List<SellerInfoDO> sellerInfoList = sellerInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(sellerInfoList)) {
            return Collections.emptyList();
        }

        return sellerInfoList.stream().map(SellerInfoDO::getSellerId).collect(Collectors.toList());
    }

    /**
     * 批量修改卖家状态
     *
     * @param sellerIdList
     */
    public void batchUpdateSellerInfo(List<Long> sellerIdList, Integer sellerStatus) {
        LambdaUpdateWrapper<SellerInfoDO> updateWrapper = Wrappers.lambdaUpdate();

        updateWrapper.in(Objects.nonNull(sellerIdList), SellerInfoDO::getSellerId, sellerIdList);
        updateWrapper.set(SellerInfoDO::getSellerStatus, sellerStatus);

        int count = sellerInfoMapper.update(null, updateWrapper);
        if (count <= 0) {
            throw new BaseBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    /**
     * 分批次查询出卖家数据
     * List中的每一个元素，是每一页的卖家数据集合JSON字符串
     *
     * @param sellerType 卖家类型
     * @return
     */
    public List<String> querySellerInfoByPage(Integer sellerType) {
        // 如果指定预热全部卖家，则查询所有卖家数据
        if (sellerType.equals(SellerTypeEnum.ALL.getCode())) {
            return queryTotalSellerInfoByPage();
        }
        // 查询匹配类型的卖家
        return queryBatchSellerInfoByPage(sellerType);
    }

    /**
     * 分批次查询出所有类型的卖家信息
     *
     * @return
     */
    private List<String> queryTotalSellerInfoByPage() {
        List<String> selfSellerInfoList = queryBatchSellerInfoByPage(SellerTypeEnum.SELF.getCode());
        List<String> popSellerInfoList = queryBatchSellerInfoByPage(SellerTypeEnum.POP.getCode());
        List<String> resultList = new ArrayList<>(selfSellerInfoList);
        resultList.addAll(popSellerInfoList);
        return resultList;
    }

    /**
     * 分批次查询出指定类型的卖家信息
     *
     * @param sellerType
     * @return
     */
    private List<String> queryBatchSellerInfoByPage(Integer sellerType) {
        List<String> batchList = new ArrayList<>();
        SellerInfoRequest request = new SellerInfoRequest();
        request.setSellerType(sellerType);
        Integer pageNum = request.getPageNo();
        // 设置每页数据量
        request.setPageSize(SkuSellerRelationConstants.QUERY_MAX_PAGE_SIZE);
        while (true) {
            Optional<List<SellerInfoResponse>> sellerInfoResponses = querySellerInfo(request);
            if (!sellerInfoResponses.isPresent()) {
                break;
            }
            List<SellerInfoResponse> sellerInfoResponseList = sellerInfoResponses.get();
            if (CollectionUtils.isEmpty(sellerInfoResponseList)) {
                break;
            }
            String batchResult = getBatchResult(sellerInfoResponseList, pageNum);
            batchList.add(batchResult);
            // 继续取下一页的用户数据
            request.setPageNo(++pageNum);
        }
        return batchList;
    }

    /**
     * @param sellerInfoResponseList
     * @param pageNum
     * @return
     */
    private String getBatchResult(List<SellerInfoResponse> sellerInfoResponseList, Integer pageNum) {
        List<String> batchResult = new ArrayList<>(sellerInfoResponseList.size());
        for (SellerInfoResponse sellerInfoResponse : sellerInfoResponseList) {
            PreheatSellerMessage message = new PreheatSellerMessage();
            message.setCachePageNo(pageNum);
            message.setSellerInfo(sellerInfoResponse);
            batchResult.add(JsonUtil.object2Json(message));
        }
        return JsonUtil.object2Json(batchResult);
    }

    /**
     * 查询出前5分钟之内的数据
     *
     * @param beforeTime 开始时间
     * @return
     */
    public List<SellerInfoDO> querySellerInfoFiveMinute(Date beforeTime) {
        List<SellerInfoDO> batchList = new ArrayList<>();
        int pageNum = 1;
        // 设置每页数据量
        int pageSize = ProductConstants.QUERY_ITEM_MAX_COUNT;
        while (true) {
            LambdaQueryWrapper<SellerInfoDO> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.ge(SellerInfoDO::getCreateTime, beforeTime);
            queryWrapper.ge(SellerInfoDO::getUpdateTime, beforeTime);

            Page<SellerInfoDO> page = new Page<>(pageNum, pageSize);
            Page<SellerInfoDO> pageResult = sellerInfoMapper.selectPage(page, queryWrapper);
            if (Objects.isNull(pageResult) || pageResult.getRecords().size() <= 0) {
                break;
            }

            batchList.addAll(pageResult.getRecords());
            // 进入下一页
            pageNum++;
        }
        return batchList;
    }
}